const crypto = require('crypto');
const config = require('./config');

/**
 * 获取SHA256加密串
 * @param str
 * @returns {PromiseLike<ArrayBuffer>}
 */
const getSHA256 = (str) => {
  return crypto.createHmac('sha256', config.SHA256_SECRET)
    .update(str)
    .digest('hex')
};

/**
 * 根据pid将数组转为树状结构
 * @param arr
 * @param topId
 * @returns {*}
 */
const getTree = (arr, pid = 'pid', topId = '0') => {
  let tree = arr.filter(item => item[pid] === topId);
  tree = tree.map(item => {
    item['list'] = arr.filter(it => it[pid] === item['_id'].toString()); // item['_id']为Object，需要转为string
    return item;
  });
  return tree;
};

module.exports = {
  getSHA256,
  getTree
};